package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.annotation.DemoAnno;
import com.itheima.tlias.exception.BusinessException;
import com.itheima.tlias.mapper.EmpExprMapper;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.pojo.*;
import com.itheima.tlias.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 06 4月 2025 15:49
 */
@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogServiceImpl empLogService;

    /**
     * 分页查询
     *
     * @param empQueryDTO
     * @return
     */
    @Override
    public PageResult<Emp> pageQuery(EmpQueryDTO empQueryDTO) {
        PageHelper.startPage(empQueryDTO.getPage(), empQueryDTO.getPageSize());
        Page<Emp> page1 = empMapper.pageQuery1(empQueryDTO);
        return new PageResult<>(page1.getTotal(), page1.getResult());

    }

    /**
     * 新增员工
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEmp(Emp emp) {
        try {
            emp.setUpdateTime(LocalDateTime.now());
            emp.setCreateTime(LocalDateTime.now());
            empMapper.addEmp(emp);
//       新增员工，员工id     @Options(useGeneratedKeys = true, keyProperty = "id")
            //获取新增员工id
            Integer id = emp.getId();
            log.info("新增员工，员工id:{}", id);
//        int i = 1/0;
//        if (true){
//            throw new Exception("手动抛出异常");
//        }
            // 设置新增员工的工作经历
            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach(expr -> {
                    expr.setEmpId(id);
                    expr.setCreatedTime(LocalDateTime.now());
                    expr.setUpdatedTime(LocalDateTime.now());
                });
                empExprMapper.addEmpExpr(exprList);
            }
        } finally {
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "执行了新增员工");
            empLogService.insertLog(empLog);
        }
    }

    /**
     * 查询所有员工
     *
     * @return
     */
    @DemoAnno
    @Override
    public List<Emp> selectList() {
        return empMapper.selectList();
    }

    /**
     * 批量删除员工
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(List<Integer> ids) {
        //增加代码的健壮性
        for (Integer id : ids) {
            // 检查该员工是否存在
            Emp emp = empMapper.findById(id);
            if (emp == null) {
                throw new BusinessException("id为" + id + "的员工不存在不能删除");
//                throw new Exception("id为" + id + "的员工不存在不能删除");
            }
        }
        //批量删除员工基本信息
        empMapper.deleteById(ids);
        //批量删除员工工作经历
        empExprMapper.delete(ids);
    }

    /**
     * 根据id查询员工
     *
     * @param uid
     * @return
     */
//    @Override
//    public Emp findById(Integer uid) {
//        Emp emp = empMapper.findById(uid);
//        Integer id = emp.getId();
//        List<EmpExpr> exprList = empExprMapper.find(id);
//        emp.setExprList(exprList);
//        return emp;
//    }
    @Override
    public Emp findById(Integer uid) {
        Emp emp = empMapper.findById(uid);
        return emp;
    }

    /*
    业务严谨性、健壮性保障措施:
1、参数校验(判断是否为空、是否不为空、参数值格式是否正确)米
2、校验数据在表中是否存在、是否不存在
3.根据状态判断业务流程是否可以继续
    */


    /**
     * 更新员工
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Emp emp) {
        //判断员工是否存在
        Long l = empMapper.existById(emp.getId());
        if (l != 1) {
            throw new BusinessException("id为" + emp.getId() + "的员工不存在，不能更新");
        }

        //更新员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        Integer id = emp.getId();
        if (!CollectionUtils.isEmpty(emp.getExprList())) {
            List<EmpExpr> exprList = emp.getExprList();
            exprList.forEach(expr -> {
                expr.setUpdatedTime(LocalDateTime.now());
                expr.setCreatedTime(LocalDateTime.now());
                expr.setEmpId(id);
            });
            empExprMapper.deleteById(id);
            empExprMapper.insert(exprList);
//            empExprMapper.update(exprList);
        }
    }

    @Override
    public LoginInfo login(Emp emp) {
        Emp empLogin = empMapper.getUsernameAndPassword(emp);
//        if (empLogin == null) {
//            throw new BusinessException("用户名或密码错误");
//        }
        log.info("123456{}",empLogin);
        if (empLogin == null) {
            return null;
        }
        //校验账户密码
//        LoginInfo loginInfo = new LoginInfo(empLogin.getId(), empLogin.getUsername(), empLogin.getName(), null);
        LoginInfo loginInfo = new LoginInfo();
        try {
            BeanUtils.copyProperties(empLogin, loginInfo);
        } catch (Exception e) {
        }
        log.info("{}",loginInfo);
        return loginInfo;
    }

    /**
     * 忘记密码
     *
     * @param forgetPwdDTO
     */
    @Override
    public void forgetPwd(ForgetPwdDTO forgetPwdDTO) {
//        判断两个密码是否一致
        if (!forgetPwdDTO.getNewPassword().equals(forgetPwdDTO.getConfirmPassword())) {
            throw new BusinessException("两次密码不一致");
        }
        //判断用户是否存在
        Emp emp = empMapper.getUserDetial(forgetPwdDTO);
        log.info("{}",emp);
        if (emp == null) {
            throw new BusinessException("用户不存在");
        }
        //用户存在，修改密码
        emp.setPassword(forgetPwdDTO.getNewPassword());
        empMapper.update(emp);
    }

    /**
     * 修改密码
     *
     * @param
     */
    @Override
    public void updatePwd(UpdatePwdDTO updatePwdDTO) {
//        判断 两次密码是否一致
        if (!updatePwdDTO.getNewPassword().equals(updatePwdDTO.getConfirmPassword())) {
            throw new BusinessException("两次密码不一致");
        }
        Emp emp =new Emp();
        emp.setPassword(updatePwdDTO.getOldPassword());
        emp.setUsername(updatePwdDTO.getUserName());
        //判断用户是否存在
        Emp usernameAndPassword = empMapper.getUsernameAndPassword(emp);
        if (usernameAndPassword == null) {
            throw new BusinessException("用户不存在");
        }
        emp.setId(usernameAndPassword.getId());
        //修改密码
        emp.setPassword(updatePwdDTO.getNewPassword());
        empMapper.update(emp);

    }

    /**
     * 根据用户名查询用户详情
     *
     * @param userName
     * @return
     */
    @Override
    public Emp getUserDetial(String userName) {
        Emp emp =  empMapper.getUserName(userName);
        //查询工作经历
        List<EmpExpr> exprList = empExprMapper.find(emp.getId());
        emp.setExprList(exprList);
        return emp;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
//    @Override
//    public PageResult<Emp> pageQuery(Integer page, Integer pageSize) {
//        //先查询总记录数
//        Long total = empMapper.count();
//        // 查询当前页数据
////        起始索引
//        Integer start = (page - 1) * pageSize;
//        List<Emp> rows = empMapper.pageQuery(start, pageSize);
//        return new PageResult<>(total, rows);
//    }

//    @Override
//    public PageResult<Emp> pageQuery(Integer page, Integer pageSize) {
//        PageHelper.startPage(page, pageSize);
//        Page<Emp> page1 = empMapper.pageQuery1(page, pageSize);
//        return new PageResult<>(page1.getTotal(), page1.getResult());
//    }
}
